<template>
    <el-dialog v-model="visible" :title="title" width="210px">
        <el-upload ref="uploadRef" class="avatar-uploader" 
            action="#" 
            :http-request="uploadReq" 
            :show-file-list="false"
            :before-upload="beforeAvatarUpload" 
            :limit="1" 
            :on-exceed="handleExceed">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/axios/index.js'
import store from '@/store/index.js'

const visible = ref(false)

const title = ref('上传头像')
const open = () => {
    uploadRef.value?.clearFiles()
    visible.value = true;
}

defineExpose({
    open
})


const close = () => {
    visible.value = false;
}

const imageUrl = ref(store.state.avatar ? store.state.avatar : '')

const beforeAvatarUpload = (rawFile) => {
    console.log(rawFile.type)
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('头像必须是图片格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('头像大小不能超过10MB!')
        return false
    }
    return true
}
const uploadRef = ref()

const handleExceed = (files) => {
    // uploadRef.value!.clearFiles()
    // const file = files[0]
    // file.uid = genFileId()
    // uploadRef.value!.handleStart(file)
}

// 设置token
const headers = ref()
const uploadReq = ({ file }) => {
    // 手动设置 headers
    const config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'token': localStorage.getItem("token")
        }
    };

    const formData = new FormData();
    formData.append('file', file);
    http.post('/sys/user/upload', formData, config).then(res=>{
        if(res.code == 200){
            store.commit('setAvatar', res.data)
            imageUrl.value = res.data
            close();
        }
    })
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>